package com.hiss.basic.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ObjectUtil;
import com.hiss.basic.client.system.ISysUserRoleService;
import com.hiss.basic.model.system.domain.SysUserRoleDomain;
import com.hiss.basic.system.mapper.SysUserRoleMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 系统用户角色 service impl
 */
@Service
public class SysUserRoleServiceImpl extends ServiceImpl<SysUserRoleMapper, SysUserRoleDomain> implements ISysUserRoleService {

    @Override
    public Collection<Long> findRoleIdListByUserId(Long userId) {
        if (ObjectUtil.isNull(userId)) {
            return ListUtil.toList();
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(SysUserRoleDomain::getUserId, userId);
        List<SysUserRoleDomain> list = list(wrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            return list.stream().map(SysUserRoleDomain::getRoleId).collect(Collectors.toSet());
        }
        return ListUtil.toList();
    }

    @Override
    public Collection<Long> findUserIdListByRoleId(Long roleId) {
        if (ObjectUtil.isNull(roleId)) {
            return ListUtil.toList();
        }
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(SysUserRoleDomain::getRoleId, roleId);
        List<SysUserRoleDomain> list = list(wrapper);
        if (CollectionUtil.isNotEmpty(list)) {
            return list.stream().map(SysUserRoleDomain::getUserId).collect(Collectors.toSet());
        }
        return ListUtil.toList();
    }

    @Override
    public void create(Long userId, List<Long> roleIdList) {
        if (CollectionUtil.isNotEmpty(roleIdList)) {
            List<SysUserRoleDomain> userRoleList = ListUtil.toList();
            for (Long item : roleIdList) {
                SysUserRoleDomain domain = new SysUserRoleDomain();
                domain.setUserId(userId);
                domain.setRoleId(item);

                userRoleList.add(domain);
            }
            saveBatch(userRoleList);
        }
    }

    @Override
    public void removeByUserId(Long userId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(SysUserRoleDomain::getUserId, userId);
        remove(wrapper);
    }

    @Override
    public void removeByRoleIdAndUserId(Long roleId, Long userId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq(SysUserRoleDomain::getRoleId, roleId);
        wrapper.eq(SysUserRoleDomain::getUserId, userId);
        remove(wrapper);
    }
}
